<?php
/**
 * Created by PhpStorm.
 * User: zhang
 * Date: 2018/7/9
 * Time: 21:04
 */

namespace app\account\model;


use app\common\model\Base;
use app\alipay\model\ConsumeManager;
use think\Config;

class GradeManager extends Base{
    const DB_NAME = "user";
    const MAX_INTEGRAL_GRADE = 2;
    private $vip;
    public function __construct()
    {
        parent::__construct();
        Config::load(APP_PATH . 'account/config.php');
        $this->vip = config('grade_id');

    }

    public function getGradeDiscountById($id){
        return $this->vip[$id]["discount"];
    }

    public function getGradeNameById($id){
        return $this->vip[$id]["name"];
    }

    public function isGrade($uid){

        $grade = $this->getUserGradeIdByUid($uid);
        if($grade >= SELF::MAX_INTEGRAL_GRADE)        //如果超过会员等级
            return false;

        $consume = new ConsumeManager();
        $cost = $consume->getConsumeCostByUid($uid);

        echo $cost ." ". $this->vip[1]["cost"] ." ". $this->vip[2]["cost"];
        if($cost > $this->vip[2]["cost"]){
            $gradeSql = "update ".SELF::DB_NAME." set agency_grade_id='2' where uid='$uid'";
            $result_msg = "恭喜升级成为会员";
        }else if($cost > $this->vip[1]["cost"]){
            $gradeSql = "update ".SELF::DB_NAME." set agency_grade_id='1' where uid='$uid'";
            $result_msg = "恭喜升级成为尊享会员";
        }else{
            return false;
        }

        if($this->mysql->updateSQL($gradeSql)){

        }

        return false;
    }

    public function getUserGradeIdByUid($uid){
        $grade_id = $this->getGradeByCustom(array("uid"=>$uid))["agency_grade_id"];

        return $grade_id;
    }

    public function getUserGradeNameByUid($uid){
        $grade_id = $this->getGradeByCustom(array("uid"=>$uid))["agency_grade_id"];

        return $this->vip[$grade_id]["name"];
    }

    private function getGradeByCustom($customKey=[]){
        if(count($customKey) == 0){
            $gradeSql = "select agency_grade_id from " .SELF::DB_NAME;
        }else{
            $condition = null;
            foreach ($customKey as $key=>$value){
                //echo "Key: $key; Value: $value<br />\n";
                if($condition==null){
                    $condition = $condition." $key='$value'";
                }else{
                    $condition = $condition." and $key='$value'";
                }

            }

            $gradeSql = "select agency_grade_id from " .SELF::DB_NAME. " where " .$condition;
        }
        $data = $this->mysql->selectSQL($gradeSql);
        if($data["agency_grade_id"]==null)
            return false;
        return $data;
    }


}